/*
@Time : 2019/5/22 0022 16:34
@Author : visons
*/
package main

import (
	"cellent_test/proto"
	"encoding/json"
	"fmt"
	"gitee.com/visons/gopkg/log"
	"github.com/davyxu/cellnet"
	"github.com/davyxu/cellnet/codec"
	"github.com/davyxu/cellnet/peer"
	"github.com/davyxu/cellnet/proc"
	"net/http"
	"reflect"

	_ "github.com/davyxu/cellnet/codec/gogopb"
	_ "github.com/davyxu/cellnet/codec/json"
	_ "github.com/davyxu/cellnet/peer/gorillaws"
	_ "github.com/davyxu/cellnet/proc/gorillaws"
)

const (
	TestAddress = "http://127.0.0.1:18802/echo"
)

// 将消息注册到系统
func init() {
	cellnet.RegisterMessageMeta(&cellnet.MessageMeta{
		Codec: codec.MustGetCodec("gogopb"),
		Type:  reflect.TypeOf((*proto.ContentACK)(nil)).Elem(),
		ID:    1234,
	})
}

func main() {
	// 创建一个事件处理队列，整个服务器只有这一个队列处理事件，服务器属于单线程服务器
	queue := cellnet.NewEventQueue()

	// 侦听在18802端口
	p := peer.NewGenericPeer("gorillaws.Acceptor", "server", TestAddress, queue)

	proc.BindProcessorHandler(p, "gorillaws.ltv", func(ev cellnet.Event) {

		switch msg := ev.Message().(type) {

		case *cellnet.SessionAccepted:
			log.Infof("server accepted")
			// 有连接断开
		case *cellnet.SessionClosed:
			log.Infof("session closed: ", ev.Session().ID())
		case *proto.ContentACK:
			log.Infof("recv: %+v %v", msg.Msg, msg.Value)

			val, exist := ev.Session().(cellnet.ContextSet).GetContext("request")
			if exist {
				if req, ok := val.(*http.Request); ok {
					raw, _ := json.Marshal(req.Header)
					fmt.Println("origin request header: %s", string(raw))
				}
			}

			ev.Session().Send(&proto.ContentACK{
				Msg:   "中文",
				Value: 1234,
			})
		}
	})

	// 开始侦听
	p.Start()

	// 事件队列开始循环
	queue.StartLoop()

	// 阻塞等待事件队列结束退出( 在另外的goroutine调用queue.StopLoop() )
	queue.Wait()

}
